package com.whq.common.http;

import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.whq.common.StringUtil;

/**
 * url工具类
 * 
 * @author wanghuaiqiang
 * 
 */
public class UrlUtil {
	private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtil.class);

	/**
	 * 根据url前缀和参数返回可以访问的url地址
	 * 
	 * @param urlPrefix
	 * @param params
	 * @param urlencodeParamValue
	 * @return
	 */
	public static final String generateUrl(String urlPrefix, Map<String, String> paramsMap, boolean urlencodeParamValue) {

		StringBuffer sbRet = new StringBuffer();
		if (urlPrefix == null) {
			urlPrefix = "";
		}
		sbRet.append(urlPrefix.trim());
		if ((paramsMap != null) && (!paramsMap.isEmpty())) {
			if (urlencodeParamValue) {
				UrlUtil.urlencodeParams(paramsMap);
			}

			int paramCount = 0;
			for (Iterator<String> iterator = paramsMap.keySet().iterator(); iterator.hasNext();) {
				String paramKey = (String) iterator.next();
				if (StringUtil.isBlank(paramKey)) {
					continue;
				}
				String paramVal = paramsMap.get(paramKey);
				if (paramVal == null) {
					paramVal = "";
				}
				if ((paramCount == 0) && (urlPrefix.indexOf("?") < 0)) {
					sbRet.append("?");
				} else {
					sbRet.append("&");
				}
				sbRet.append(paramKey.trim() + "=");
				sbRet.append(paramVal);

				paramCount++;
			}
		}

		return sbRet.toString();
	}

	/**
	 * Urlencode所有参数
	 * 
	 * @param businessParams
	 */
	public static void urlencodeParams(Map<String, String> businessParams) {
		if (businessParams == null) {
			return;
		}
	
		for (Iterator<String> iterator = businessParams.keySet().iterator(); iterator.hasNext();) {
			String paramKey = (String) iterator.next();
			String paramVal = businessParams.get(paramKey);
			if (paramVal == null) {
				paramVal = "";
			}
			try {
				paramVal = URLEncoder.encode(paramVal, "UTF-8");
			} catch (Exception e) {
				LOGGER.error("URLEncoder(" + paramVal + ") exception: ", e);
			}
	
			businessParams.put(paramKey, paramVal);
		}
	}
}
